package com.guojian.sso.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.OncePerRequestFilter;

/**
 * SSO 登录验证流程  client1 client2 clientX.. ssoServer
 * 
 * 1.clientFilter检测client是否登录,如果未登录或者登录超时则 重定向到ssoServer
 * 2.ssoServer 检查是否已经登录,如果未登录则直接弹出登录窗口,登录完成后,设置ST标识.并跳转到之前的页面,且携带ST参数
 * 3.clientFilter 检测ST参数已经携带,就直接到ssoServer验证,验证通过设置cookie,下次cookie会自动带上
 * 
 * 拦截所有请求并进行认证
 * @author guoJian
 *
 */
public class AuthFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		String userName = request.getParameter("user_name");
		HttpSession httpSession = request.getSession();

		Object attr = httpSession.getAttribute("user_name");

		if (attr != null) {
			userName = attr.toString();
		}

		if ("guojian".equalsIgnoreCase(userName)) {
			httpSession.setAttribute("user_name", userName);
			filterChain.doFilter(request, response);
		} else {
			httpSession.removeAttribute("user_name");
			//response.setStatus(500);
			//response.getOutputStream().write("not auth".getBytes());
			//response.sendRedirect("baidu.com");//location: http://localhost:9080/baidu.com
			response.sendRedirect("http://baidu.com");
			
		}

	}

}
